class ProjectsController < ApplicationController
  before_filter :only_teachers,
                :except => [:index, :show]
  before_filter :get_project
  # Shows projects list
  #
  def index
    @projects = Project.find(:all)
    
    respond_to do |wants|
      wants.html
      wants.xml   { render :xml => @projects.to_xml }
    end
  end
  
  # Shows a single project
  #
  def show
    respond_to do |wants|
      wants.html
      wants.xml { render :xml => @project.to_xml }
    end
  end
  
  # Shows form to edit a project. Only for GET requests.
  #
  def edit
    
  end
  
  # Updates project
  #
  def update
    if @project.update_attributes(params[:project])
      respond_to do |wants|
        wants.html  { redirect_to project_url(@project) }
        wants.js
        wants.xml   { head :ok }
      end
    else
      respond_to do |wants|
        wants.html do
          flash.now[:error] = 'Unable to save project'
          render :action => "edit"
        end
        wants.js    { render :nothing => true, :status => 500 }
        wants.xml   { render :xml => @project.errors.to_xml }
      end
    end
  end
  
  # Shows form to create a new project. Only for GET requests.
  #
  def new
    @project = Project.new
  end
  
  # Creates new project
  #
  def create
    @project = Project.new(params[:project])
    
    if @project.save
      respond_to do |wants|
        wants.html  { redirect_to project_url(@project) }
        wants.xml   { head :created, :location => project_url(@project) }
      end
    else
      respond_to do |wants|
        wants.html do
          flash.now[:error] = 'Unable to create project'
          render :action => "new"
        end
        wants.js    { render :nothing => true, :status => 500 }
        wants.xml   { render :xml => @project.errors.to_xml }
      end
    end
  end
  
  # Deletes project
  #
  def destroy
    @project.destroy
    
    respond_to do |wants|
      wants.html do
        flash[:note] = 'Project deleted'
        redirect_to projects_url
      end
      wants.js  { head :ok }
      wants.xml { head :ok }
    end
  end
private
  # If params[:id] is set, retrieves @project
  #
  def get_project
    unless params[:id].nil? || params[:id].blank?
      @project = Project.find(params[:id])
      raise if @project.nil?
    end
    return true
  rescue
    respond_to do |wants|
      wants.html { render :text => "The project you're looking for doesn't exist!", :layout => true, :status => 404 }
      wants.js   { render :nothing => true, :status => 404 }
      wants.xml  { head :not_found }
    end
    return false
  end
end
